// 云函数入口文件 - 获取和保存公众号openid
const cloud = require('wx-server-sdk')
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV })
const db = cloud.database();
const _ = db.command;
// 数据库用户表
const users = db.collection("用户表");

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  // 获取来源公众号用户的各种id
  var gzh_openid = wxContext.FROM_OPENID;
  var unionid = wxContext.FROM_UNIONID;
  // 根据unionId保存公众号的openid
  if(gzh_openid && unionid){
    var res = await users.where({
      unionid: _.eq(unionid)
    }).update({data:{
      gzh_openid: gzh_openid
    }})
    if(res.stats.updated > 0){
      return 'UPDATE'
    }
  }
  return 'KEEP';
}